import { _decorator, Component, Sprite } from 'cc';
import { MapPosition } from './MapPosition';
import { addP2D, KKP2D, KKSpriteFrameInfo } from '@coldcloude/kakera';
import { CharacterController } from './CharacterController';
import { A_STAND, D_DOWN } from './Constants';
import { buildUINodeEx, NodeEx } from './NodeEx';
import { SpriteAnimeResource } from './SpriteAnimeResource';
import { KKAnimator } from './Animator';
const { ccclass } = _decorator;

@ccclass('AnimeCharacter')
export class AnimeCharacter extends Component {

    //config

    animeRes:SpriteAnimeResource;

    //init

    animator:KKAnimator;

    characterController:CharacterController;

    mapPos:MapPosition;

    _move(delta:KKP2D){
        this.mapPos.position = addP2D(this.mapPos.position,delta);
    }

    _moveTo(target:KKP2D){
        this.mapPos.position = target;
    }

    init() {
        //pos
        this.mapPos = this.getComponent(MapPosition);
        if(!this.mapPos){
            this.mapPos = this.addComponent(MapPosition);
        }
        //animator
        this.animeRes.init();
        const spriteNode = buildUINodeEx();
        this.node.addChild(spriteNode);
        const sprite = spriteNode.addComponent(Sprite);
        this.animator = new KKAnimator(this.animeRes.hub,this.animeRes.atlas,spriteNode,sprite);
        //set controller
        this.characterController = this.getComponent(CharacterController);
        if(!this.characterController){
            this.characterController = this.addComponent(CharacterController);
        }
        this.characterController.onMove((delta)=>this._move(delta));
        this.characterController.onMoveTo((target)=>this._moveTo(target));
        this.characterController.onSetDirectionAction((param)=>this.animator.setDirectionAction(param));
        //init
        this.animator.setDirectionAction({direction:D_DOWN,action:A_STAND});
    }

    render(dt:number){
        this.animator.render(dt);
    }
}
